using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Windows.Forms;

namespace Cache
{
    class MapPosition
    {
        private const string CVE_KEY_ROOT = "Software\\ViaVirtualEarth\\WinformsEarth";
        RegistryKey CVE_key;
        public double lat, lon;
        public int zoom;


        // Update the lat/lon/zoom of the map position in a single call
        public void setPosition(double lat_arg, double lon_arg, int zoom_arg)
        {
            lat = lat_arg;
            lon = lon_arg;
            zoom = zoom_arg;
        }

        // Initialize a MapPosition using explicit latitude, longitude and zooms
        public MapPosition(double lat, double lon, int zoom)
        {
            setPosition(lat, lon, zoom);
        }

        // Default constructor initializes MapPosition from the registry
        public MapPosition()
        {
            // Get last known state of the map out of the registry, if it exists
            CVE_key = Registry.CurrentUser.OpenSubKey(CVE_KEY_ROOT, true);

            if (CVE_key == null)
            {
                CVE_key = Registry.CurrentUser.CreateSubKey(CVE_KEY_ROOT);
            }

            if (CVE_key.GetValue("bm_last_lat") != null)
            {
                setPosition(
                    double.Parse((string)CVE_key.GetValue("bm_last_lat")),
                    double.Parse((string)CVE_key.GetValue("bm_last_lon")),
                    Int32.Parse((string)CVE_key.GetValue("bm_last_zoom")));
            }
            else
            {
                MapPosition defaultpos = MapPosition.USA();

                this.lat = defaultpos.lat;
                this.lon = defaultpos.lon;
                this.zoom = defaultpos.zoom;
            }

        }

        // Save map state into the registry
        public void save()
        {
            CVE_key.SetValue("bm_last_lat", (object)lat.ToString());
            CVE_key.SetValue("bm_last_lon", (object)lon.ToString());
            CVE_key.SetValue("bm_last_zoom", (object)zoom.ToString());
        }

        public void updateLabels(Label lat_label, Label lon_label, Label zoom_label)
        {
            lat_label.Text = lat.ToString();
            lon_label.Text = lon.ToString();
            zoom_label.Text = zoom.ToString();
        }


        # region Predefined positions

        static public MapPosition USA()
        {
            return new MapPosition(40, -97, 4);
        }

        public static MapPosition World()
        {
            return new MapPosition(0, 0, 1);
        }

        # endregion
    }
}
